package com.stockz.ui.swing.watchlist.widget;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import com.stockz.core.util.SpringUtil;
import com.stockz.ui.swing.widget.JTextField;
import com.stockz.watchlist.manager.WatchListManager;
import com.stockz.watchlist.model.WatchList;

public class CreateNewWatchListActionListener implements ActionListener, KeyListener {

	private JTextField nameTextField;
	private AddToWatchListMenu menu;
	private final WatchListManager watchListManager;
	
	public CreateNewWatchListActionListener(JTextField nameTextField, AddToWatchListMenu callback) {
		setNameTextField(nameTextField);
		setCallback(callback);
		watchListManager = SpringUtil.getApplicationContext().getBean(WatchListManager.class);
	}
	
	@Override
	public void keyPressed(KeyEvent e) {}
	@Override
	public void keyTyped(KeyEvent e) {}
	@Override
	public void keyReleased(KeyEvent e) {
		if(e.getKeyCode() == KeyEvent.VK_ENTER){
			createNewWatchList();
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		createNewWatchList();
	}

	public void createNewWatchList(){
		System.out.println("Creating watchlist with name : "+nameTextField.getText());
		WatchList watchList = new WatchList();
		watchList.setName(nameTextField.getText());
		watchListManager.create(watchList);
		
		
		
		if(menu != null){
			menu.addWatchListToUI(watchList);
		}
		nameTextField.setText("");
	}
	
	public JTextField getNameTextField() {
		return nameTextField;
	}

	public void setNameTextField(JTextField nameTextField) {
		if(nameTextField == null){
			throw new IllegalArgumentException("Name text field for watchlist can not be null");
		}
		this.nameTextField = nameTextField;
	}

	public AddWatchListToUICallback getCallback() {
		return menu;
	}

	public void setCallback(AddToWatchListMenu callback) {
		this.menu = callback;
	}

}
